/***************************************************************************************
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University
*
* NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*          http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/

#include "sdb.h"
static WP *free_ = NULL;
static WP *head=NULL;
static WP wp_pool[NR_WP] = {};
void init_wp_pool() {
  int i;
  for (i = 0; i < NR_WP; i++) {
    wp_pool[i].NO = i;
    wp_pool[i].next = (i == NR_WP - 1 ? NULL : &wp_pool[i + 1]);
  }

  head = NULL;
  free_ = wp_pool;
}
WP* new_wp(char *args,word_t res){
  WP *n=NULL;
  WP *p=NULL;
  n = free_;
  p = head;
  if (free_==NULL)
  {
    assert(0);
  }
  free_ = free_->next;
  n->next = NULL;
  n->val = res;
  // strcpy(n->expression, args);
  memset(n->expression,'$',strlen(args));
  memcpy(n->expression,args,strlen(args));
  //n->expression = *args;
  if(p ==NULL){
    head = n;
    p = head;
  }
  else{
    while (p->next)
    {
      p = p->next;
    }
    p->next = n;
  }
  return n;
};



void free_wp(int num){
  //extern WP * head;
  WP *n=NULL;
  WP *p=head;
 // WP *del = head;
  n = free_;
  // p = head;
  // del = head;
  if (p == NULL)
  {
    assert(0);
  }
  if (p->NO == num)
  {
    while (n->next !=NULL)
    {
      n=n->next;
    }
    n->next =p;
    p = p->next;
  }
  else{
    while (p->next->NO != num)
    {
      p = p->next;
    }

    if (n == NULL)
    {
      n = p->next;
      free_ = n;
    }
    else{
      while (n->next !=NULL)
      {
        n=n->next;
      }
      n->next =p->next ;
    }
    p->next=p->next->next;
  }
  

}
void info_watchpoint(){
  WP*p = head;
  printf("num \t val\t expression\n");
  while (p->next)
  {
    printf("%d\t%ld\t%s\n",p->NO,p->val,p->expression);
    p = p->next;
  }
  printf("%d\t%ld\t%s\n",p->NO,p->val,p->expression);
 }
#ifdef CONFIG_WATCHPOINT
  void stop_head(){
    WP* n = head;
    bool success;
    word_t now ;
    if (n)
    {
      while (n->next)
      {
        now = expr(n->expression,&success);
        if (n->val != now)
        {
          n->val = now;
          nemu_state.state = NEMU_STOP;
        }
        n=n->next;
      }
      now = expr(n->expression,&success);
      if (n->val != now)
      {
        n->val = now;
        nemu_state.state = NEMU_STOP;
      }
    }
  }
#endif
